package ops.controller;

import ops.WindowManager;
import ops.model.EntityAlreadyExistsException;
import ops.model.Teacher;
import ops.model.manager.EntityController;
import ops.model.manager.TeacherManager;
import ops.view.TeacherRegisterPanel;

public class TeacherController {
	
	private TeacherManager teacherManager;	
	
	private boolean adding;

	public TeacherController() {
		teacherManager = EntityController.getInstance().getTeacherManager();
	}

	public void startAddProcess() {
		adding = true;
	}
	
	public void endAddProcess() {
		adding = false;
	}
	
	private void add(String name, String email, Boolean exclusive, String hierarchy, String subordination) {
		Long code = teacherManager.nextLongID();
		
		Teacher subject = new Teacher();
		subject.setCode(code);
		subject.setName(name);
		subject.setEmail(email);
		subject.setExclusive(exclusive);
		subject.setHierarchy(hierarchy);
		subject.setSubordination(subordination);
		
		try {
			teacherManager.add(subject);
			teacherManager.save();
		} catch (EntityAlreadyExistsException e) {
			e.printStackTrace();
		}
	}
	
	private void edit(Long code, String name, String email, boolean exclusive, String hierarchy, String subordination) {
		Teacher subject = teacherManager.getObjectByKey(code);		
		subject.setName(name);
		subject.setEmail(email);
		subject.setExclusive(exclusive);
		subject.setHierarchy(hierarchy);
		subject.setSubordination(subordination);
		
		teacherManager.save();
	}
	
	public void saveTeacher(Long code, String name, String email, Boolean exclusive, String hierarchy, String subordination) {
		if (adding) {
			add(name, email, exclusive, hierarchy, subordination);
			
			adding = false;
		} else {
			edit(code, name, email, exclusive, hierarchy, subordination);
		}
		
		updateTable();
	}
	
	public void removeTeacher(Long code) {
		teacherManager.remove(code);
		teacherManager.save();
		
		updateTable();
	}
	
	public void updateTable() {
		TeacherRegisterPanel panel = getPanel();
		
		panel.clearTable();
		
		for (Teacher teacher : teacherManager.getMap().values()) {
			panel.addRowToTable(teacher.getCode(), teacher.getName(), teacher.getEmail(), teacher.isExclusive(), teacher.getHierarchy(), teacher.getSubordination());
		}
	}
	
	private TeacherRegisterPanel getPanel() {
		return (TeacherRegisterPanel) WindowManager.getInstance().getPanel("register.teachers");
	}
}
